<template>
  <div class='m-courseDetail'>
    <el-form class="form" ref='form' label-width="120px" :model="form" :rules='rules'>
      <el-form-item label="课程名称：" prop='name'>
        <el-input type="text" placeholder="请输入课程名称" v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="课程人数：" prop='number'>
        <el-input type="number" placeholder="请输入课程人数" :max='99999' v-model="form.number"></el-input>
      </el-form-item>
      <el-form-item label="上课时间：">
        <el-date-picker
          v-model="form.time"
          type="date"
          value-format='timestamp'
          placeholder="请选择上课时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="课程状态：" prop='status' v-if='type === "set"'>
        <a-select v-model='form.status' :options='courseStatusList' />
      </el-form-item>

      <el-form-item class='createTheFormItem' v-for='(attr, attrIndex) in attrList' :key='attr.id' :label='attr.name + "："'  >
        <!-- 选择分类 -->
        <div v-if='attr.value_type === "0"' :class='attr.is_require === "1" ? "" : "m-courseDetail_autoAttr"'>
          <el-checkbox-group v-model="attr.selects">
            <el-checkbox v-for='classItem in attr.classes' 
              :key='classItem.id' :label="classItem.id">
              <span>{{ classItem.name }}</span>
              <!-- 再显示子分类 -->
              <el-select v-if='classItem.child && classItem.child.length'
                v-model='classItem.selects'
                multiple collapse-tags clearable
              >
                <el-option
                  v-for='(item) in classItem.child'
                  :key='item.id'
                  :label='item.name'
                  :value='item.id'
                />
              </el-select>
            </el-checkbox>
          </el-checkbox-group>
          <i v-if='attr.is_require !== "1"' class='el-icon-close' @click='closeAutoAttr(attrIndex)'></i>
        </div>
        <!-- 输入类型 -->
        <div v-else  :class='attr.is_require === "1" ? "" : "m-courseDetail_autoAttr"'>
          <el-input :class='attr.is_require === "1" ? "form-content" : ""' type='text' v-model.trim='attr.classes[0].name' />
          <i v-if='attr.is_require !== "1"' class='el-icon-close' @click='closeAutoAttr(attrIndex)'></i>
        </div>
      </el-form-item>

      <el-form-item label="课程属性：">
        <attr-list :limitCreateNum='1'
          :isShowSelectBox='false'
          ref='attrList' aType='0' @getSku='getSku'
        />
      </el-form-item>
      <el-form-item label="商品价格：" prop='price'>
        <el-input placeholder="请输入商品价格" type='number' v-model="form.price"></el-input>
      </el-form-item>
      <el-form-item label='kpi选择：'>
        <el-checkbox v-model='form.isKpi' /> 是否 kpi
      </el-form-item>
      <el-form-item align='left'>
        <el-button type="primary" @click="confirm">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import AttrList from '@/components/business/List'
import { mapMutations } from 'vuex'
import attrMixin from '@/mixins/attrs'

export default {
  name: 'course_detail',

  components: {
    AttrList
  },

  mixins: [attrMixin],

  data() {
    return {
      form: {
        name: '',
        number: '',
        time: '',
        status: '',
        attr: '',
        isKpi: false,
        price: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入课程名称', trigger: 'blur' },
          { max: 20, min: 2, message: '长度为 2 - 20 个字符', trigger: 'blur' }
        ],
        number: [
          { required: true, message: '请输入课程人数', trigger: 'blur' }
        ],
        // time: [
        //   { required: true, message: '请输入上课时间', trigger: 'blur' }
        // ],
        status: [
          { required: true, message: '请选择课程状态', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请填写商品价格', trigger: 'blur' }
        ]
      },
      courseStatusList: [
        { label: '进行中', value: 1 },
        { label: '已结束', value: 3 }
      ],
      ifRequesting: false,
      type: 'add',
      id: ''
    }
  },

  async created() {
    const { type, id } = this.$route.query
    this.type = type
    this.id = id
    await this.getAttributes()
    if (type !== 'set') {
      this.$set(this.rules, 'status', [])
    } else {
      this.getMine()
    }
  },

  methods: {
    ...mapMutations(['setTabRoutes']),

    async getMine() {
      const { code, data } = await this.$api.courseGetInfo({ aId: this.id })
      if (code === 0) {
        this.form.name = data.name
        this.form.number = parseInt(data.skus[0] ? data.skus[0].quantity : 0, 10)
        this.form.status = parseInt(data.status, 10)
        this.form.price = parseInt(data.skus[0].price, 10)
        this.form.isKpi = data.is_kpi === '1'
        this.form.time = data.class_time + '000'
        // 根据必须和非必须，进行分开格式化
        this.formatInfoData(data.attrs.filter(v => v.is_require === '1'))
        this.contactAttrData()
        this.$refs.attrList.formatDetailDataToAttrList(data.attrs.filter(v => v.is_require !== '1'))
      }
    },

    async create() {
      this.ifRequesting = true
      const isUpdate = this.type === 'set'
      const { name, price, number, status, time, isKpi } = this.form
      const params = {
        aId: this.id,
        aMerchantId: this.aFirmId,
        aName: name,
        aSkus: [{ aPrice: price, aQuantity: number }],
        aIsReleased: isUpdate ? status : 1,
        aAttrs: this.formatOutputData(),
        aIsKpi: isKpi ? 1 : 0
      }
      if (time) {
        params.aClassTime = (parseInt(time, 10) / 1000)
      }
      const { code } = await this.$api[!isUpdate ? 'courseCreateInfo' : 'courseModifyInfo'](params)
      this.ifRequesting = false
      if (code === 0) {
        this.__notify(isUpdate ? '修改成功' : '添加成功')
        this.setTabRoutes({ type: 'add', obj: this.getRouterInfoAccordingName('course') })
        this.$router.push({ name: 'course' })
      }
    },

    confirm() {
      if (this.ifRequesting) return
      this.$refs.form.validate((valid) => {
        if (!valid) return
        this.create()
      })
    },

    reset() {
      this.$refs.form.resetFields()
    },

    // attr
    async getAttributes() {
      const { code, data } = await this.$api.utilsGetAllClasses({
        aMerchantId: this.aFirmId,
        aType: '0'
      })
      if (code === 0) {
        this.formatAttrAndClassData(data.list)
      }
    },

    closeAutoAttr(index) {
      let _i = index
      this.attrList.forEach((v, i) => {
        if (i < index && !v.skuId) _i -= 1
      })
      this.$refs.attrList.closeSku(_i)
    }
  }
}
</script>

<style lang='less'>
  .m-courseDetail {
    .addValue-list {
      display: flex;
      align-items: center;
      padding-bottom: 20px;
      .icon {
        margin-left: 20px;
      }
      &-child {
        padding-bottom: 10px;
      }
    }
    .form-data {
      width: 100%;
    }
    &_autoAttr {
      display: flex;
      align-items: center;
      .el-cascader, .el-input {
        flex: 1;
        margin-right: 15px;
      }
    }
    .createTheFormItem {
      .el-checkbox-group {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        width: 100%;
      }
      .el-checkbox {
        // flex: 1;
        width: 50%;
        display: flex;
        align-items: center;
        padding-right: 10px;
        box-sizing: border-box;
        &:nth-child(n+3) {
          padding-top: 10px;
        }
      }
      .el-checkbox+.el-checkbox {
        margin-left: 0;
      }
    }
  }
</style>